import { useCallback } from "react";
import { observer } from "mobx-react";
import { FC } from "@tarojs/taro";
import { View, Text, Image } from "@tarojs/components";
import FlexScrollView from "@/components/FlexScrollView";
import { DynamicColors, GStyleSheet } from "@/utils/DarkMode";
import {
  networkConfigTypes,
  IProduct,
  getMainGroupProductWithID
} from "@/config/product";
import { initCategory, ICategory, correctProduct } from "@/config/utils";
import { useStatePlus } from "@/hooks/useStatePlus";
import { useMount } from "@/hooks/useMount";

import configWifiModel from "../models/configWifi";

const dstyles = GStyleSheet.create({
  container: {
    flex: 1,
    width: "100%",
    flexDirection: "row",
    display: "flex",
    overflow: "hidden"
  },
  sidebar: {
    height: "100%",
    width: "30%",
  },
  list: {
    background: DynamicColors.screenBackgroundGaryColor,
  },
  listItem: {
    display: "flex",
    alignItems: "center",
    padding: "18px 15px",
    fontSize: 14,
    color: DynamicColors.normalTextGaryColor,
  },
  icon: {
    width: 30,
    height: 30,
  },
  active: {
    backgroundColor: "#fff",
    color: "#1b1b1b",
  },
  productList: {
    height: "100%",
    width: "70%",
    backgroundColor: "#fff",
  },
  products: {
    textAlign: "center",
    fontSize: 12,
    display: "flex",
    flexDirection: "column",
    gap: 16,
    marginBottom: 20,
    color: "#999",
  },
  productsWrapper: {
    display: "flex",
    flexWrap: "wrap",
    gap: 16,
  },
  productItem: {
    width: "28%",
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    gap: 6,
    position: "relative",
  },
  custom: {
    position: "absolute",
    top: -5,
    right: -12,
    fontSize: 10,
    background: DynamicColors.tintColor,
    color: "#fff",
    padding: "2px 4px",
    borderRadius: 8,
  },
});

interface ICategoryExpand {
  m2mProtoc: string;
  networkConfigType?: string[];
  configName: string;
  usingAdapter?: string;
  gidExpand: string;
}

// 需要显示的品类配网类型支持列表
const allCategoryProductList: ICategoryExpand[] = [
  { m2mProtoc: "WIFI", networkConfigType: [networkConfigTypes.TNetworkConfigTypeSoftAp], configName: '(WiFi)', gidExpand: 'wifi' },
  { m2mProtoc: "BLE", usingAdapter: "GizAdapterWifiBle", configName: '(BLE)', gidExpand: 'ble' },
  { m2mProtoc: "WIFI", usingAdapter: "GizAdapterWifiBle", networkConfigType: [networkConfigTypes.TNetworkConfigTypeBTWifi, networkConfigTypes.TNetworkConfigTypeSoftAp], configName: '(WiFi+BLE)', gidExpand: 'wifiBle' },
];

function getFakeProduct({ category, expand }: { category: ICategory, expand: ICategoryExpand }) {
  const product: IProduct = {
    ...category,
    ...expand,
    productKey: '11',
    productSecret: '12',
    language: {
      zh: {
        PL_PRODUCT_NAME: category.name + expand.configName,
      }
    },
    softAPSSIDPrefix: "XPG-GAgent-",
    softAPPassword: "123456789",
    wxTemplateId: "com.gizwits.wx.ai",
    templateConfig: { featureList: [] },
  }
  return correctProduct(product, []);
}


interface IState {
  categoryList: ICategory[];
  selectCategory: ICategory | null;
}

const CategoryList: FC = () => {
  const styles = dstyles.useDynamicStyle();
  const [{ categoryList, selectCategory }, setState] = useStatePlus<IState>({
    categoryList: [],
    selectCategory: null,
  });

  const goToWifiSelect = useCallback(
    ({ category, expand }: { category: ICategory, expand: ICategoryExpand }) => () => {
      let product: IProduct
      console.log('ICategory', category)
      // 有配置gid的就尝试去找各个group的产品
      if (category.gid) {
        const gid = `${category.gid}_${expand.gidExpand}`
        product = getMainGroupProductWithID(gid)
      }
      // product为空生成一个假的
      if (!product) {
        product = getFakeProduct({ category, expand })
      }
      console.log('getFakeProduct', product)
      configWifiModel.curPk = product.productKey
      configWifiModel.goToConfig(product)
      if (category.id === 34) {
        // 34代表是其他，不限制配网pk
        configWifiModel.setNotFilterPk();
      }
    },
    []
  );

  useMount(() => {
    const list = initCategory();
    setState({ categoryList: list, selectCategory: list[0] });
  });

  const categoryItemClick = useCallback(
    (cat: ICategory) => () => {
      setState({ selectCategory: cat });
    },
    [setState]
  );

  return (
    <View style={styles.container}>
      <View style={styles.sidebar}>
        <FlexScrollView id='categoryList'>
          <View style={styles.list}>
            {categoryList.map((categoryItem) => {
              return (
                <View
                  key={categoryItem.id}
                  style={{
                    ...styles.listItem,
                    ...(selectCategory?.id === categoryItem.id
                      ? styles.active
                      : {}),
                  }}
                  onClick={categoryItemClick(categoryItem)}
                >
                  <Text>{categoryItem.name}</Text>
                </View>
              );
            })}
          </View>
        </FlexScrollView>
      </View>
      <View style={styles.productList}>
        <FlexScrollView id='productList'>
          <View style={{}}>
            {selectCategory?.children.map((item) => {
              return (
                <View key={item.id} style={styles.products}>
                  <Text>{item.name}</Text>
                  <View style={styles.productsWrapper}>
                    {item.children.map((product) => {
                      return allCategoryProductList.map((subItem) => {
                        return (
                          <View
                            key={product.id}
                            style={styles.productItem}
                            onClick={goToWifiSelect({ category: product, expand: subItem })}
                          >
                            <Image src={product.icon} style={styles.icon} />
                            <Text>{product.name}</Text>
                            <Text>{subItem.configName}</Text>
                            {/* <Text>{product.id}</Text> */}
                            {/* {product.is_customize && (
                              <View style={styles.custom}>自定义</View>
                            )} */}
                          </View>
                        );
                      })
                    })}
                  </View>
                </View>
              );
            })}
          </View>
        </FlexScrollView>
      </View>
    </View>
  );
};

export default observer(CategoryList);
